<?php
namespace Admin\Controller;
use Admin\Logic\StoreLogic;
use Think\Log;

class StoreController extends BaseController{
	//店铺等级 
	public function store_grade(){
		$model =  M('store_grade');
		$count = $model->where('1=1')->count();
		$Page = new \Think\Page($count,10);
		$list = $model->order('sg_id')->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign('list',$list);
		$show = $Page->show();
		$this->assign('page',$show);
		$this->display();
	}
	
	public function grade_info(){
		$sg_id = I('sg_id');
		if($sg_id){
			$info = M('store_grade')->where("sg_id=$sg_id")->find();
			$this->assign('info',$info);
		}
		$this->display();
	}
	

    /**
     * 开通app
     */
    public function openApp()
    {
        $store_id = I('store_id');
        $store = M('store s')
        ->field('s.*,u.mobile as mobile')
        ->join('ty_users u on u.user_id = s.user_id','left')
        ->where(['s.store_id'=>$store_id])
        ->find();
        $url = "https://shop.zczmer.com/WXAPI/app/add_member?mobile=".$store['mobile']."&store_name=".preg_replace('/[^0-9]/', '', $store['mobile'])."&seller_name=".$store['seller_name'].'&pid=8';
       
        $res = httpRequest($url,'GET');
        echo $res;exit;
    }
	public function export_store(){
	    
        $action=I('action');$store_id=I('store_id'); //店铺赋值。
        if($action=='qingkong' && !empty($store_id)){
            M('goods')->where('store_id='.$store_id)->setField([
                'sales_sum'=>'0'
            ]);

            $aa = M('order_goods a')
                ->field('a.*,b.order_status')
                ->join('ty_order b on a.order_id=b.order_id','LEFT')
                ->where("a.store_id=".$store_id." and b.order_status in(0,1,2,4)")->select();

            foreach($aa as $v){
                M('goods')->where('store_id='.$store_id.' and goods_id='.$v['goods_id'])->setInc('sales_sum',$v['goods_num']);
            }
            exit;
        }
		$model =  M('store');
		// 20181121 去掉后台显示的限制，把自营店铺和非自营店铺都显示出来 亮 START
//		$map['is_own_shop'] = 0 ;
        // 20181121 去掉后台显示的限制，把自营店铺和非自营店铺都显示出来 亮 END
		$grade_id = I("grade_id");
		if($grade_id>0) $map['grade_id'] = $grade_id;
		$sc_id =I('sc_id');
		if(!empty($sc_id) && $sc_id!='undefined') $map['sc_id'] = $sc_id;
		if(I("fenbu_id")) $map['fenbu_id'] = I("fenbu_id");
		$store_state = I("store_state");
		if(!empty($store_state) && $store_state!='undefined')$map['store_state'] = $store_state;
		$fast_flag = I("fast_flag");
		if($fast_flag!='' &&  $fast_flag!='undefined')$map['fast_flag'] = $fast_flag;
		$seller_name = I('seller_name');
		if($seller_name && $seller_name!='undefined') $map['seller_name'] = array('like',"%$seller_name%");
		$store_name = I('store_name');
		if($store_name) $map['store_name'] = array('like',"%$store_name%");
		
		$list = $model->where($map)->order('store_id desc')->select();
		foreach($list as $key=>$v){
			$users=M('users')->where('user_id='.$v['user_id'])->find();
			$list[$key]['nickname']=$users['nickname']; //$v['user_id']
         
        }
        
        $strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">ID</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">店铺名称</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">卖家账号</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">所属会员</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台扣点</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">进驻日期</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">到期时间</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">状态</td>';
    	$strTable .= '</tr>';
    	

    	foreach($list as $k=>$val){
	    if($val['store_state'] == 1){
	        $sorts_status = '开启';
	    }else{
	         $sorts_status = '关闭';
	    }
    		$strTable .= '<tr>';
			$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['store_id'].'</td>';
    		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['store_name'].'</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['seller_name'].'</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['user_name'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['koudian'].' </td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.\date('Y-m-d H:i:s',$val['store_time']).'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.\date('Y-m-d H:i:s',$val['store_time_end']).'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$sorts_status.'</td>';

    		$strTable .= '</tr>';
    	}
    	$strTable .='</table>';
    	unset($list);
    	downloadExcel($strTable,'联鑫壹天达店铺列表');
    	exit();
	
	}
	    /*
    *商品导出
    */
    public function exclleGoods(){
        $store_id = I('store_id');
       
        if(empty($store_id)){
            $json_arr = array('status'=>0,'msg'=>'没有store_id' );
            $json_str = json_encode($json_arr);
            exit($json_str);
        }
        $store = M('store')->field('store_name')->where(['store_id'=>$store_id])->find();
        ignore_user_abort(true);
        set_time_limit(0);
        //找出还在上架通过审核的产品规格
        $list = M('spec_goods_price a')
        ->field('g.goods_name, a.goods_id, s.store_name, s.store_id, GROUP_CONCAT(gm.image_url SEPARATOR "||") AS image_urls, b.name as bname, g.cat_id2, g.original_img, g.cat_id1, g.cat_id3, a.sku, a.key_name, a.price, a.qipi_num, a.spu, g.keywords')
        ->join('ty_goods g on g.goods_id = a.goods_id', 'LEFT')
        ->join('ty_store s on s.store_id = g.store_id', 'LEFT')
        ->join('ty_brand b on b.id = g.brand_id', 'LEFT')
        ->join('ty_goods_images gm on gm.goods_id = a.goods_id', 'LEFT')
        ->where(['g.is_on_sale' => 1, 'g.goods_state' => 1, 'g.store_id' => $store_id])
        ->group('a.key')
      
        ->select();
     
       import("Org.Util.PHPExcel");
			import("Org.Util.PHPExcel.Worksheet.Drawing");
			import("Org.Util.PHPExcel.Writer.Excel2007");
			
			$objPHPExcel = new \PHPExcel();
			$objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
			$objPHPExcel->setActiveSheetIndex(0);
			$objActSheet = $objPHPExcel->getActiveSheet();
	        $objActSheet->setCellValue('A1', '商城一级分类');
	        $objActSheet->setCellValue('B1', '商城二级分类');
	        $objActSheet->setCellValue('D1', '商城三级分类');
	        $objActSheet->setCellValue('D1', '商品名称');
	        $objActSheet->setCellValue('E1', '品牌名称');
	        $objActSheet->setCellValue('F1', '商城货号');
	        $objActSheet->setCellValue('G1', '规格');
	        $objActSheet->setCellValue('H1', '型号');
	        $objActSheet->setCellValue('I1', '销售价');
	        $objActSheet->setCellValue('J1', '起订量');
	        $objActSheet->setCellValue('K1', '盒数');
	        $objActSheet->setCellValue('L1', '盒价');
	        $objActSheet->setCellValue('M1', '箱数');
	        $objActSheet->setCellValue('N1', '箱价');
	        $objActSheet->setCellValue('O1', '单位');
	        $objActSheet->setCellValue('P1', '包装');
	        $objActSheet->setCellValue('Q1', '关键词');
	        $objActSheet->setCellValue('R1', '区域价1');
	        $objActSheet->setCellValue('S1', '区域价2');
	        $objActSheet->setCellValue('T1', '区域价3');
	        $objActSheet->setCellValue('U1', '图片1');
	        $objActSheet->setCellValue('V1', '图片2');
	        $objActSheet->setCellValue('W1', '图片3');
	        $objActSheet->setCellValue('X1', '图片4');
	        $objActSheet->setCellValue('Y1', '图片5');
	        $objActSheet->setCellValue('Z1', '商家');
	        $i=2;
      
        foreach ($list as $k=>$v){
            if(!empty($v['image_urls'])){
                $v['image_urls'] = explode('||', $v['image_urls']);
                if (count($v['image_urls']) > 4) {
                    $v['image_urls'] = array_slice($v['image_urls'], 0, 4);
                }
                foreach ($v['image_urls'] as $key=>$val){
                    $val = 'https://yc.zczmer.com'.$val;
                    $v['image_urls'][$key] = $val;
                }
            }
       
            //获取分类名称
            if(!empty($v['cat_id1'])){
                $cat_id1 = M('goods_category')->field('name')->where(['id'=>$v['cat_id1']])->find();
                $v['cat_id1'] = $cat_id1['name'];
            }
            if(!empty($v['cat_id2'])){
                $cat_id2 = M('goods_category')->field('name')->where(['id'=>$v['cat_id2']])->find();
                $v['cat_id2'] = $cat_id2['name'];
            }
            if(!empty($v['cat_id3'])){
                $cat_id3 = M('goods_category')->field('name')->where(['id'=>$v['cat_id3']])->find();
                $v['cat_id3'] = $cat_id3['name'];
            }
          
            $objActSheet->setCellValue('A'.$i, $v['cat_id1']);
            $objActSheet->setCellValue('B'.$i, $v['cat_id2']);
            $objActSheet->setCellValue('C'.$i, $v['cat_id3']);
            $objActSheet->setCellValue('D'.$i, $v['goods_name']);
            $objActSheet->setCellValue('E'.$i, $v['bname']);
            $objActSheet->setCellValue('F'.$i, $v['sku']);
            $objActSheet->setCellValue('G'.$i, $v['key_name']);
            $objActSheet->setCellValue('H'.$i, '');
            $objActSheet->setCellValue('I'.$i, $v['price']);
            $objActSheet->setCellValue('J'.$i, $v['qipi_num']);
            $objActSheet->setCellValue('K'.$i, '');
            $objActSheet->setCellValue('L'.$i, '');
            $objActSheet->setCellValue('M'.$i, '');
            $objActSheet->setCellValue('N'.$i, '');
            $objActSheet->setCellValue('O'.$i, $v['spu']);
            $objActSheet->setCellValue('P'.$i, '');
            $objActSheet->setCellValue('Q'.$i, $v['keywords']);
            $objActSheet->setCellValue('R'.$i, '');
            $objActSheet->setCellValue('S'.$i, '');
            $objActSheet->setCellValue('T'.$i, '');
            $objActSheet->setCellValue('U'.$i, 'https://yc.zczmer.com'.$v['original_img']);
            $objActSheet->setCellValue('V'.$i, $v['image_urls'][0]);
            $objActSheet->setCellValue('W'.$i, $v['image_urls'][1]);
            $objActSheet->setCellValue('X'.$i, $v['image_urls'][2]);
            $objActSheet->setCellValue('Y'.$i, $v['image_urls'][3]);
            $objActSheet->setCellValue('Z'.$i, $v['store_name']);
            $i++;
        }
        $fileName = '联鑫壹天达'.$store['store_name'].'商品导出';
        $date = date("Y-m-d",time());
        $fileName .= "_{$date}.xlsx";
        $fileName = iconv("utf-8", "gb2312", $fileName);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header("Content-Transfer-Encoding:binary");
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output'); //文件通过浏览器下载
			exit;	
	
    }
	
	    /**
     *  库存分部修改
     */
     public function fenbuKuncun(){
         $store_id = I('store_id');
         if(empty($store_id)){
             die;
         }
         $fenbu = M('fenbu')->where('fenbu_id !=0')->select();
         $store = M('store')->where(['store_id'=>$store_id])->find();
         if(empty($store['fenbu_goods'])){
             foreach ($fenbu as $k=>$v){
                 $arr[$k]['fenbu_id'] = $v['fenbu_id'];
                 $arr[$k]['sales_sum'] = 0;
                 $arr[$k]['sorts'] = 500;
            }
             M('store')->where(['store_id'=>$store_id])->save(['fenbu_goods'=>json_encode($arr)]);
         }
         $storeInfo = M('store')->where(['store_id'=>$store_id])->find();
         $fenbu_goods = json_decode($storeInfo['fenbu_goods'],true);
         foreach ($fenbu as $k=>$v){
             if($v['fenbu_id'] == $fenbu_goods[$k]['fenbu_id']){
                    $fenbu[$k]['sales_sum'] = $fenbu_goods[$k]['sales_sum'];
                    $fenbu[$k]['sorts'] = $fenbu_goods[$k]['sorts'];
             }
         }
         if(IS_POST){
             $sales_sum = I('sales_sum');
             $sorts = I('sorts');
            
            //  die;
            $arr = [];
             foreach ($sales_sum as $k=>$v){
                 $arr[$k]['fenbu_id'] = $k;
                 $arr[$k]['sales_sum'] = $v;
                 $arr[$k]['sorts'] = $sorts[$k];
                //  M('fenbu_goods')->where(['fenbu_id'=>$k,'goods_id'=>$goods_id])->save(['sales_sum'=>$v,'sorts'=>$sorts[$k]]);
             }
              sort($arr);
              M('store')->where(['store_id'=>$store_id])->save(['fenbu_goods'=>json_encode($arr)]);
              //店铺下面商品
              $godosList = M('goods')->where(['store_id'=>$store_id,'is_on_sale'=>1,'goods_state'=>1])->select();
              foreach ($godosList as $k=>$v){
                  foreach ($arr as $key=>$val){
                      $fenbuGoodsInfo = M('fenbu_goods')->where(['fenbu_id'=>$val['fenbu_id'],'goods_id'=>$v['goods_id']])->count();
                      if($fenbuGoodsInfo<=0){
                          //没有数据添加
                          M('fenbu_goods')->where(['fenbu_id'=>$val['fenbu_id'],'goods_id'=>$v['goods_id']])->add(
                              [
                                  'sales_sum'=>$val['sales_sum'],
                                  'sorts'=>$val['sorts'],
                                  'goods_id'=>$v['goods_id'],
                                  'fenbu_id'=>$val['fenbu_id']
                              ]
                              );
                      }else{
                          //修改
                          M('fenbu_goods')->where(['fenbu_id'=>$val['fenbu_id'],'goods_id'=>$v['goods_id']])->save(['sales_sum'=>$val['sales_sum'],'sorts'=>$val['sorts']]);
                      }
                  }
                  
              }
             $this->success("操作成功!!!",U('Admin/Store/fenbuKuncun?store_id='.$store_id));
             die;
         }
        $this->assign('fenbu',$fenbu);
        $this->display();  
     }
	
	public function grade_info_save(){
		$data = I('post.');
		if($data['sg_id'] > 0 || $data['act']=='del'){
			if($data['act'] == 'del'){
				if(M('store')->where(array('grade_id'=>$data['del_id']))->count()>0){
					respose('该等级下有开通店铺，不得删除');
				}else{
					$r = M('store_grade')->where("sg_id=".$data['del_id'])->delete();
					respose(1);
				}
			}else{
				$r = M('store_grade')->where("sg_id=".$data['sg_id'])->save($data);
			}
		}else{
			$r = M('store_grade')->add($data);
		}
		if($r){
			$this->success('编辑成功',U('Store/store_grade'));
		}else{
			$this->error('提交失败');
		}
	}
	
	public function store_class(){
		$model =  M('store_class');
		$count = $model->where('1=1')->count();
		$Page = new \Think\Page($count,25);
		$list = $model->order('sc_sort')->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign('list',$list);
		$show = $Page->show();
		$this->assign('page',$show);
		$this->display();
	}
	
	//店铺分类
	public function class_info(){
		$sc_id = I('sc_id');
		if($sc_id){
			$info = M('store_class')->where("sc_id=$sc_id")->find();
			$this->assign('info',$info);
		}
		$this->display();
	}
	
	public function class_info_save(){
		$data = I('post.');
		if($data['sc_id'] > 0 || $data['act']=='del'){
			if($data['act']== 'del'){
				if(M('store')->where(array('sc_id'=>$data['del_id']))->count()>0){
					respose('该分类下有开通店铺，不得删除');
				}else{
					$r = M('store_class')->where("sc_id=".$data['del_id'])->delete();
					respose(1);
				}
			}else{
				$r = M('store_class')->where("sc_id=".$data['sc_id'])->save($data);
			}
		}else{
			$r = M('store_class')->add($data);
		}
		if($r){
			$this->success('编辑成功',U('Store/store_class'));
		}else{
			$this->error('提交失败');
		}
	}
	
	//普通店铺列表
	public function store_list(){
		$action=I('action');$store_id=I('store_id');$datas=I('datas'); //店铺赋值。
		   if($action=='qingkong' && !empty($store_id)){ //echo $store_id;exit;
            M('goods')->where('store_id='.$store_id)->setField([
                'sales_sum'=>'0'
            ]);

            $aa = M('order_goods a')
                ->field('sum(a.goods_num) goods_num,a.goods_id,b.order_status')
                ->join('ty_order b on a.order_id=b.order_id','LEFT')
                ->where("a.store_id=".$store_id." and b.order_status in(0,1,2)")
				->group('a.goods_id')
				->select();

            foreach($aa as $v){
                M('goods')->where('store_id='.$store_id.' and goods_id='.$v['goods_id'])->setInc('sales_sum',$v['goods_num']);
            }
            exit;
        }elseif($action=='fast' && !empty($datas)){
            $datas=\explode(',',$datas);
            foreach($datas as $v){
                M('store')->where(['store_id'=>$v])->save(['fast_flag'=>1]);
            }
            echo 1;
            exit;
        }elseif($action=='san_code' && !empty($datas)) {
               $datas = \explode(',', $datas);
               foreach ($datas as $v) {
                   M('store')->where(['store_id'=>$v])->save(['open_san'=>1]);
               }
       }elseif($action=='close_san_code' && !empty($datas)) {
               $datas = \explode(',', $datas);
               foreach ($datas as $v) {
                   M('store')->where(['store_id'=>$v])->save(['open_san'=>0]);
               }
       }

		$model =  M('store');
		// 20181121 去掉后台显示的限制，把自营店铺和非自营店铺都显示出来 亮 START
//		$map['is_own_shop'] = 0 ;
        // 20181121 去掉后台显示的限制，把自营店铺和非自营店铺都显示出来 亮 END
		$grade_id = I("grade_id");
		if($grade_id>0) $map['grade_id'] = $grade_id;
		$sc_id =I('sc_id');
		if($sc_id!='') $map['sc_id'] = $sc_id;
		if(I("fenbu_id")){
			$map['fenbu_id'] = I("fenbu_id");
		}else{
			$map['fenbu_id'] = session("fenbu_id");
		}
			
		$store_state = I("store_state");
		if($store_state!='')$map['store_state'] = $store_state;
		$seller_name = I('seller_name');
		if($seller_name) $map['seller_name'] = array('like',"%$seller_name%");
		$store_name = I('store_name');
		if($store_name) $map['store_name'] = array('like',"%$store_name%");
        $fast_flag = I("fast_flag");
        if($fast_flag!='')$map['fast_flag'] = $fast_flag;
        $open_san = I("open_san");
        if($open_san!='')$map['open_san'] = $open_san;
		$count = $model->where($map)->count();
		
		$Page = new \Think\Page2($count);
		$list = $model->where($map)->order('store_id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
	   //dump($list);
		foreach($list as $key=>$v){
			$users=M('users')->where('user_id='.$v['user_id'])->find();
			 if(!empty($users)){
			     	$list[$key]['nickname']=$users['nickname']; //$v['user_id']
			 }
			 //dump($users);
        
			$seller=M('seller')->where(['seller_name'=>$v['seller_name']])->find();
			if(!empty($seller)){
			    $list[$key]['seller_id']=$seller['seller_id']; //$v['user_id']
			}
		
		
			
            if($v['store_logo'] != '/Public/images/mylogo.jpg'){
                $list[$key]['store_logo'] = C('MYOSS')['url2'].$v['store_logo']; //by sofwu oss图片处理
            }

            //查看有没有授权广西
            $sysn = M('sync_account')->where(['store_id'=>$v['store_id']])->find();
            if(!empty($sysn)){
                $list[$key]['sync_account'] = 1;
            }else{
                $list[$key]['sync_account'] = 2;
            }

		}
			    
        
		//echo \json_encode($list);
		$this->assign('list',$list);
		
		$show = $Page->show();
		$this->assign('page',$show); 
		$store_grade = M('store_grade')->getField('sg_id,sg_name');

		$this->assign('store_grade',$store_grade);$this->assign('fenbu_list',$this->fenbu_list);
		$this->assign('store_class',M('store_class')->getField('sc_id,sc_name'));
		$this->display();
	}
	
	/*添加店铺*/
	public function store_add(){
		if(IS_POST){
			$store_name = I('store_name');
			$user_name = I('user_name');
			$seller_name = I('seller_name');
			$fenbu_id = session('fenbu_id');
			if(empty($user_name)){
				$this->error("所属会员不能为空！");
			}
            $where = [];
            if($fenbu_id != 0 ){
                $where = ['fenbu_id'=>$fenbu_id];
            }
			if(M('store')->where("store_name='$store_name'")->where($where)->count()>0){
				$this->error("店铺名称已存在");
			}
			if(M('seller')->where("seller_name='$seller_name'")->count()>0){
				$this->error("此名称已被占用");
			}
			$user_id = M('users')->where("mobile='$user_name'")->getField('user_id');
			if(!empty($user_id)){
				if(M('store')->where(array('user_id'=>$user_id))->count()>0){
					$this->error("该会员已经申请开通过店铺");
				}
			}
			$store = array('store_name'=>$store_name,'user_name'=>$user_name,'store_state'=>1,
					'seller_name'=>$seller_name,'password'=>I('password'),
					'store_time'=>time(),'is_own_shop'=>I('is_own_shop'),'fenbu_id'=>$fenbu_id
			);
			
			$storeLogic = new StoreLogic();
			if($storeLogic->addStore($store)){
				if(I('is_own_shop') == 1){
				    $storeInfo = M('store')->where(['mobile'=>$user_name])->find();
				    if(!empty($storeInfo)){
                        M('users')->where()->save(['store_id'=>$storeInfo['store_id']]);
                    }
					$this->success('店铺添加成功',U('Store/store_own_list'));
				}else{
					$this->success('店铺添加成功',U('Store/store_list'));
				}
				exit;
			}else{
				$this->error("店铺添加失败");
			}
		}
		$is_own_shop = I('is_own_shop',1);
		$this->assign('is_own_shop',$is_own_shop);
		$this->display();
	}
	
	public function out_list(){
		$key = I('key');
		$fenbu_id = session('fenbu_id');
		$where = [];
		if($fenbu_id != 0){
		    $where = ['fenbu_id'=>$fenbu_id];
        }
		$users=M('users')->where($where)->where("nickname like '%".$key."%' or mobile like '%".$key."%'")->select();
		$res = array('code'=>'200','olist'=>$users);
		respose($res);
		}

	//区域店铺列表
	public function store_list_quyu(){
		$model =  M('store');
		$sc_id =I('sc_id');
		if($store_state>0)$map['store_state'] = $store_state;
		$store_name = I('store_name');
		if($store_name) $map['store_name'] = array('like',"%$store_name%");
		//$map['quyu_stop'] = array('neq',"");
		
		$count = $model->where($map)->count();
		$Page = new \Think\Page($count,10);
		$list = $model->where($map)->order('quyu_stop desc')->limit($Page->firstRow.','.$Page->listRows)->select();
		foreach($list as $key=>$v){
            if($v['store_logo'] != '/Public/images/mylogo.jpg'){
                $list[$key]['store_logo'] = C('MYOSS')['url2'].$v['store_logo']; //by sofwu oss图片处理
            }
			$users=M('users')->where('user_id='.$v['user_id'])->find();
			$list[$key]['nickname']=$users['nickname']; //$v['user_id']
		}
		$this->assign('list',$list);
		$show = $Page->show();
		$this->assign('page',$show);
		$this->display();
	}
	/**
	 *
	 * */
	public function store_list_yijia_quyu(){
        $model =  M('store');
        $sc_id =I('sc_id');
        if($store_state>0)$map['store_state'] = $store_state;
        $store_name = I('store_name');
        if($store_name) $map['store_name'] = array('like',"%$store_name%");
        //$map['quyu_stop'] = array('neq',"");

        $count = $model->where($map)->count();
        $Page = new \Think\Page($count,10);
        $list = $model->where($map)->order('store_yijia desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach($list as $key=>$v){
            if($v['store_logo'] != '/Public/images/mylogo.jpg'){
                $list[$key]['store_logo'] = C('MYOSS')['url2'].$v['store_logo']; //by sofwu oss图片处理
            }
            $users=M('users')->where('user_id='.$v['user_id'])->find();
            $list[$key]['nickname']=$users['nickname']; //$v['user_id']
        }
//        dump($list);
        $this->assign('list',$list);
        $show = $Page->show();
        $this->assign('page',$show);
        $this->display();
    }

	public function store_list_quyu_price(){
		$model =  M('store');
		$sc_id =I('sc_id');
		if($store_state>0)$map['store_state'] = $store_state;
		$store_name = I('store_name');
		if($store_name) $map['store_name'] = array('like',"%$store_name%");
		//$map['quyu_stop'] = array('neq',"");
		
		$count = $model->where($map)->count();
		$Page = new \Think\Page($count,10);
		$list = $model->where($map)->order('quyu_price desc')->limit($Page->firstRow.','.$Page->listRows)->select();
		foreach($list as $key=>$v){
            if($v['store_logo'] != '/Public/images/mylogo.jpg'){
                $list[$key]['store_logo'] = C('MYOSS')['url2'].$v['store_logo']; //by sofwu oss图片处理
            }
			$users=M('users')->where('user_id='.$v['user_id'])->find();
			$list[$key]['nickname']=$users['nickname']; //$v['user_id']
		}
		$this->assign('list',$list);
		$show = $Page->show();
		$this->assign('page',$show);
		$this->display();
	}

    public function store_bianji_quyu(){
        $store_id=I('store_id',0);
        $action=I('action');
        $del_id=I('del_id');
        $store =  M('store')->where('store_id='.$store_id)->find();
        if($store['quyu_stop']){
            $quyu_stops=\json_decode($store['quyu_stop'],true);
//			foreach($quyu_stops as $key=>$vs){
//				if(empty($vs)){
//					unset($quyu_stops[$key]);
//				}
//			}
            M('store')->where('store_id='.$store_id)->setField(['quyu_stop'=>\json_encode($quyu_stops)]);
        }else
            $quyu_stops=[];

        if($action=="alldel"){
            M('store')->where('store_id='.$store_id)->setField(['quyu_stop'=>'']);exit;
        }

        if($action=="del"){
            $newarr=[];
            foreach($quyu_stops as $v){
                if($del_id!=$v)
                    array_push($newarr,$v);
            }
            M('store')->where('store_id='.$store_id)->setField(['quyu_stop'=>\json_encode($newarr)]);exit;
        }

        if($action=="add"){
            $value=I('value');
            $value=\explode(',',$value);

            foreach($value as $v){
                if(strpos($store['quyu_stop'],'"'.$v.'",') === false){
                    array_push($quyu_stops,$v);
                }
            }//echo \json_encode($quyu_stops);

            M('store')->where('store_id='.$store_id)->setField(['quyu_stop'=>\json_encode($quyu_stops)]);
            exit;
        }

        if(join(',',$quyu_stops))
            $quyu_stops=M('fenbu')->where('fenbu_id in('.join(',',$quyu_stops).')')->select();

        $this->assign('store',$store);
        $this->assign('quyu_stops',$quyu_stops);
        $this->display();
    }

    public function store_bianji_yijia_quyu(){
        $store_id=I('store_id',0);
        $action=I('action');
        $del_id=I('del_id');
        $store =  M('store')->where('store_id='.$store_id)->find();
        if($store['yijia_quyu'])
            $quyu_price=\json_decode($store['yijia_quyu']);
        else
            $quyu_price=[];

        if($action=="alldel"){
            M('store')->where('store_id='.$store_id)->setField(['store_yijia'=>0,'yijia_quyu'=>'']);
            M('goods')->where("store_id = $store_id")->save(array('yijia_quyu'=>'')); // 根据条件保存修改的数据
            exit;
        }

        if($action=="del"){
            $newarr=[];
            foreach($quyu_price as $key=>$v){
                if($del_id==$v->id)
                    unset($quyu_price[$key]);
            }
            sort($quyu_price);
            M('store')->where('store_id='.$store_id)->setField(['yijia_quyu'=>\json_encode($quyu_price)]);
            M('goods')->where("store_id = $store_id")->save(array('yijia_quyu'=>\json_encode($quyu_price)));
            exit;
        }

        if($action=="edit"){
            foreach($quyu_price as $key=>$v){
                if(I('myid')==$v->id){
                    $quyu_price[$key]->hl=I('zhi');
                }
            }
            M('goods')->where("store_id = $store_id")->save(array('yijia_quyu'=>\json_encode($quyu_price)));
            M('store')->where('store_id='.$store_id)->setField(['yijia_quyu'=>\json_encode($quyu_price)]);
            exit;
        }

        if($action=="add"){
            $value=I('value');
            $pd=0;
            foreach($quyu_price as $vs){
                if($vs->id==$value)
                    $pd=1;break;
            }
            if($pd==0){
                $quyu_price[]=['id'=>$value,'hl'=>100];
            }
            M('goods')->where("store_id = $store_id")->save(array('yijia_quyu'=>\json_encode($quyu_price)));
            M('store')->where('store_id='.$store_id)->setField(['yijia_quyu'=>\json_encode($quyu_price)]);
            exit;
        }

        $quyu_price=\json_decode(M('store')->where('store_id='.$store_id)->getField('yijia_quyu'),true); //重新获取区域价格。

        foreach($quyu_price as $key=>$v){
            $quyu_price[$key]['name']=M('fenbu')->where('fenbu_id='.$v['id'])->getField('fenbu_name');
        }
        // dump($quyu_price);
        $this->assign('store',$store);
        $this->assign('quyu_price',$quyu_price);
        $this->display();
    }


    public function store_bianji_quyu_price(){
		$store_id=I('store_id',0);
		$action=I('action');
		$del_id=I('del_id');
		$store =  M('store')->where('store_id='.$store_id)->find();
		if($store['quyu_price'])
			$quyu_price=\json_decode($store['quyu_price']);
		else
			$quyu_price=[];
			 
		if($action=="alldel"){
			 M('store')->where('store_id='.$store_id)->setField(['quyu_price'=>'']);exit;
		}
		
		if($action=="del"){
			$newarr=[];
			foreach($quyu_price as $key=>$v){
				if($del_id==$v->id)
				unset($quyu_price[$key]);
			}
			 M('store')->where('store_id='.$store_id)->setField(['quyu_price'=>\json_encode($quyu_price)]);exit;
		}
		
		if($action=="edit"){
			foreach($quyu_price as $key=>$v){
				if(I('myid')==$v->id){
					$quyu_price[$key]->hl=I('zhi');
				}
			}
			 M('store')->where('store_id='.$store_id)->setField(['quyu_price'=>\json_encode($quyu_price)]);
			 exit;
		}
		
		if($action=="add"){
			$value=I('value');
			$pd=0;
				foreach($quyu_price as $vs){
					if($vs->id==$value)
					$pd=1;break;
				}
				if($pd==0){
					$quyu_price[]=['id'=>$value,'hl'=>100];
				}
				
			M('store')->where('store_id='.$store_id)->setField(['quyu_price'=>\json_encode($quyu_price)]);
			exit;
		} 
		
		$quyu_price=\json_decode(M('store')->where('store_id='.$store_id)->getField('quyu_price'),true); //重新获取区域价格。
	
		foreach($quyu_price as $key=>$v){
			$quyu_price[$key]['name']=M('fenbu')->where('fenbu_id='.$v['id'])->getField('fenbu_name');
		}
	
		$this->assign('store',$store);
		$this->assign('quyu_price',$quyu_price);
		$this->display();
	}
	
	public function quyu_sousuo(){
        $key=I('key');
        if($key){
            $fenlei=M('fenbu')->where('fenbu_name like "%'.$key.'%"')->limit(15)->select();

            foreach($fenlei as $v){
                echo '<li rel="'.$v['fenbu_id'].'" rev="'.$v['fenbu_name'].'">'.$v['fenbu_name'].'</li>';
            }
        }
        exit;
	}

	/*验证店铺名称，店铺登陆账号*/
	public function store_check(){
		$store_name = I('store_name');
		$seller_name = I('seller_name');
		$user_name = I('user_name');
		$res = array('stat'=>'ok');
		$fenbu_id = session('fenbu_id');
		$where = [];
		if($fenbu_id != 0){
            $where = ['fenbu_id'=>$fenbu_id];
        }
		if($store_name && M('store')->where("store_name='$store_name'")->where($where)->count()>0){
			$res = array('stat'=>'fail','msg'=>'店铺名称已存在');
		}
		
		if(!empty($user_name)){
			if(!check_email($user_name) && !check_mobile($user_name)){
				$res = array('stat'=>'fail','msg'=>'所属会员账号格式有误');
			}
			$pd=M('users')->where("mobile='$user_name'")->find();
			if(M('seller')->where("user_id=".$pd['user_id'])->count()>0){
				$res = array('stat'=>'fail','msg'=>'该会员已开店');
			}
		}

		if($seller_name && M('seller')->where("seller_name='$seller_name'")->count()>0){
			$res = array('stat'=>'fail','msg'=>'店铺账号已被占用');
		}
		respose($res);
	}
	
	/*编辑自营店铺*/
	public function store_edit(){
		if(IS_POST){
			$data = I('post.');
			if(M('store')->where("store_id=".$data['store_id'])->save($data)){
				$this->success('编辑店铺成功',U('Store/store_own_list'));
				exit;
			}else{
				$this->error('编辑失败');
			}
		}
		$store_id = I('store_id',0);
		$store = M('store')->where("store_id=$store_id")->find();
		$this->assign('store',$store);
		$this->display();
	}
	
	//编辑外驻店铺
	public function store_info_edit(){
		if(IS_POST){
			$map = I('post.'); //echo strtotime('2022-02-20');
			$store = $map['store']; //\print_r($store['store_time_end']);exit;

			unset($map['store']);
			$store_id=$map['store_id']; 
            $old_sale_num = M('store')->where(['store_id'=>$store_id])->getField('sale_num');
			$pdkoudian=M('store')->where(array('store_id'=>$store_id))->getField('koudian'); //判断扣点是否更改 
			if($pdkoudian!=$store['koudian']){
				M('goods')->where(array('store_id'=>$store_id))->setField('points',$store['koudian']); //更新产品扣点
			} 
			M('goods')->where(array('store_id'=>$store_id))->setField('fenbu_id',$store['fenbu_id']); //更新产品扣点
            $d = M('store')->where(array('store_id'=>$store_id))->find();
			$store['store_time_end']=strtotime($store['store_time_end']); //更新到期时间
            if(!empty($store['fenbu_koudian'])){
                $fenbuKoudianArr = [];
                foreach ($store['fenbu'] as $k=>$v){
                    $fenbuKoudianArr[$k]['fenbu_id'] = $v;
                    $fenbuKoudianArr[$k]['fenbu_koudian'] = $store['fenbu_koudian'][$k];
                }
                $store['fenbu_koudian'] = json_encode($fenbuKoudianArr);

                M('goods')->where(array('store_id'=>$store_id))->setField('fenbu_koudian',$store['fenbu_koudian']);
            }
			$a = M('store')->where(array('store_id'=>$store_id))->save($store);
			$xinxipd=M('store_apply')->where('user_id='.$store['user_id'])->getField('id');
			$map['user_id']=$store['user_id'];
			$map['store_name']=$store['store_name'];
			$map['seller_name']=M('seller')->where('store_id='.$store_id)->getField('seller_name');

			unset($map['store_id']);

			if($xinxipd){
				$b = M('store_apply')->where(array('user_id'=>$store['user_id']))->save($map);
			}else{
				$b = M('store_apply')->where(array('user_id'=>$store['user_id']))->add($map);
			}
			
			if(!empty($map['store_class'])){
                //   dump($map['fenbu_id']);
                $store_classData = $map['store_class'];
                $store_class = json_encode($map['store_class']); //\print_r($store['store_time_end']);exit;
                unset($map['store_class']);
                
                M('store')->where(['store_id'=>$store_id])->save(['sc_id'=>$store_class]);
            }
			
			//修改密码
            $password = $map['password'];
            $password2 = $map['password2'];
            if($password != '' && $password != $password2){
                exit($this->error('两次输入密码不同'));
            }
            if($password == '' && $password2 == ''){
                unset($_POST['password']);
            }else{
				$users_password['password']=encrypt($_POST['password']);
				$c = M('users')->where(array('user_id'=>$store['user_id']))->save($users_password);
            }



			//修改密码
			//if($b || $a || $c){

//            if($d['store_state']!=$store['store_state']){
//                if($store['store_state'] == 0){
//                    //关闭店铺，同时下架店铺所有商品
//                    M('goods')->where(array('store_id'=>$store_id,'goods_state'=>['not in','2,3']))->save(['is_on_sale'=>0,'goods_state'=>0]);
//                }else{
//                    M('goods')->where(array('store_id'=>$store_id,'goods_state'=>['not in','2,3']))->save(['is_on_sale'=>1,'goods_state'=>1]);
//                }
//            }

                if($store['sale_num'] != $old_sale_num){
//                        M('goods')->where(array('store_id'=>$store_id))->setDec('sales_sum',$old_sale_num);
                         M('goods')->where(array('store_id'=>$store_id))->setInc('sales_sum',$store['sale_num']);

//                        M('goods')->where(array('store_id'=>$store_id,'sales_sum'=>['lt',$store['sale_num']]))->save(['sales_sum'=>$store['sale_num']]);
                    }
                //}

				
				$this->success('编辑店铺成功',U('Store/store_list'));
				exit;
			// }else{
			// 	$this->error('编辑失败');
			// }
		}
		
		//show内容
		$store_id = I('store_id');
        $fenbuList = [];
		if($store_id>0){
			$store = M('store')->where("store_id=$store_id")->find();
			$this->assign('store',$store);
			$apply = M('store_apply')->where('user_id='.$store['user_id'])->find();
			$this->assign('apply',$apply);

			if(!empty($store['fenbu_koudian'])){
                $fenbuList = json_decode($store['fenbu_koudian'],true);
                foreach ($fenbuList as $k=>$g){
                    $fenbuList[$k]['fenbu_name'] = M('fenbu')->where(['fenbu_id'=>$g['fenbu_id']])->getField('fenbu_name');
                }
            }else{
                //显示所有分部，默认为0
                $fenbuList = M('fenbu')->select();
            }
            $store['sc_id'] = json_decode($store['sc_id'],true);
		}else{
            //显示所有分部，默认为0
            $fenbuList = M('fenbu')->select();
        }
		$this->assign('store_grade',M('store_grade')->getField('sg_id,sg_name'));
// 		$this->assign('store_class',M('store_class')->order('sc_sort')->getField('sc_id,sc_name'));
		$this->assign('users',M('users')->where('user_id='.$store['user_id'])->find());


        $catList = M('store_class')->where(['level'=>1])->order('sc_sort asc')->select();
     
        foreach ($catList as $k=>$v){
            if(!empty($store['sc_id'])){
                // dump($v['id']);
                // dump($store['sc_id']);
                if(in_array($v['sc_id'],$store['sc_id'])){
                    $catList[$k]['status'] = 1;
                }else{
                    $catList[$k]['status'] = 0;
                }
            }
        }
        // dump($catList);

		$province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
		$this->assign('province',$province);
		$this->assign('catList',$catList);
		$this->assign('fenbuList',$fenbuList);
		$this->assign('fenbu_list',$this->fenbu_list);
		$this->display();
	}
	
	/*删除店铺*/
	public function store_del(){
		$store_id = I('del_id');
		if($store_id > 1){
			$store = M('store')->where("store_id=$store_id")->find();
			if(M('goods')->where("store_id=$store_id")->count()>0){
				respose('该店铺有发布商品，不得删除');
			}else{
				M('store')->where("store_id=$store_id")->delete();
				M('seller')->where("store_id=$store_id")->delete();
				adminLog("删除店铺".$store['store_name']);
				respose(1);
			}
		}else{
			respose('基础自营店，不得删除');
		}
	}
	
	//店铺信息
	public function store_info(){
		$store_id = I('store_id');
		$store = M('store')->where("store_id=".$store_id)->find();
		$this->assign('store',$store);
		$apply = M('store_apply')->where("user_id=".$store['user_id'])->find();
		$this->assign('apply',$apply);
		$bind_class_list = M('store_bind_class')->where("store_id=".$store_id)->select();
		$goods_class = M('goods_category')->getField('id,name');
		for($i = 0, $j = count($bind_class_list); $i < $j; $i++) {
			$bind_class_list[$i]['class_1_name'] = $goods_class[$bind_class_list[$i]['class_1']];
			$bind_class_list[$i]['class_2_name'] = $goods_class[$bind_class_list[$i]['class_2']];
			$bind_class_list[$i]['class_3_name'] = $goods_class[$bind_class_list[$i]['class_3']];
		}
		$this->assign('bind_class_list',$bind_class_list);
		$this->display();
	}
	
	//自营店铺列表
	public function store_own_list(){
		$model =  M('store');
		$map['is_own_shop'] = 1 ;
		$grade_id = I("grade_id");
		if($grade_id>0) $map['grade_id'] = $grade_id;
		$sc_id =I('sc_id');
		if($sc_id>0) $map['sc_id'] = $sc_id;
		$store_state = I("store_state");
		if($store_state>0)$map['store_state'] = $store_state;
		$seller_name = I('seller_name');
		if($seller_name) $map['seller_name'] = array('like',"%$seller_name%");
		$store_name = I('store_name');
		if($store_name) $map['store_name'] = array('like',"%$store_name%");
		$count = $model->where($map)->count();
		$Page = new \Think\Page($count,10);
		$list = $model->where($map)->order('store_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign('list',$list);	
		$show = $Page->show();
		$this->assign('page',$show);
		$store_grade = M('store_grade')->getField('sg_id,sg_name');
		$this->assign('store_grade',$store_grade);
		$this->assign('store_class',M('store_class')->getField('sc_id,sc_name'));
		$this->display();
	}
	
	//店铺申请列表
	public function apply_list(){
		$model =  M('store_apply');
		$map['apply_state'] = array('neq',1);
		$grade_id = I("grade_id");
		if($grade_id>0) $map['grade_id'] = $grade_id;
		$sc_id =I('sc_id');
		if($sc_id>0) $map['sc_id'] = $sc_id;
		$seller_name = I('seller_name');
		if($seller_name) $map['seller_name'] = array('like',"%$seller_name%");
		$store_name = I('store_name');
		if($store_name) $map['store_name'] = array('like',"%$store_name%");
		$count = $model->where($map)->count();
		$Page = new \Think\Page($count,10);
		$list = $model->where($map)->order('add_time desc')->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign('list',$list);
		$show = $Page->show();
		$this->assign('page',$show);
		$this->assign('store_grade',M('store_grade')->getField('sg_id,sg_name'));
		$this->assign('store_class',M('store_class')->getField('sc_id,sc_name'));
		$this->display();
	}
	
	public function apply_del(){
		$id = I('del_id');
		if($id && M('store_apply')->where(array('id'=>$id))->delete()){
			$this->success('操作成功',U('Store/apply_list'));
		}else{
			$this->error('操作失败');
		}
	}
	//经营类目申请列表
	public function apply_class_list(){
		$state = I('state');
		if($state != ""){
			$bind_class = M('store_bind_class')->where(array('state'=>$state))->select();
		}else{
			$bind_class = M('store_bind_class')->select();
		}		
		$goods_class = M('goods_category')->getField('id,name');
		for($i = 0, $j = count($bind_class); $i < $j; $i++) {
			$bind_class[$i]['class_1_name'] = $goods_class[$bind_class[$i]['class_1']];
			$bind_class[$i]['class_2_name'] = $goods_class[$bind_class[$i]['class_2']];
			$bind_class[$i]['class_3_name'] = $goods_class[$bind_class[$i]['class_3']];
			$store = M('store')->where("store_id=".$bind_class[$i]['store_id'])->find();
			$bind_class[$i]['store_name'] = $store['store_name'];
			$bind_class[$i]['seller_name'] = $store['seller_name'];
		}
		$this->assign('bind_class',$bind_class);
		$this->display();
	}
	
	//查看-添加店铺经营类目
	public function store_class_info(){
		$store_id = I('store_id');
		$store = M('store')->where(array('store_id'=>$store_id))->find();
		$this->assign('store',$store);
		if(IS_POST){
			$data = I('post.');
			$data['state'] = empty($store['is_own_shop']) ? 0 : 1;
			$where = 'class_3 ='.$data['class_3'].' and store_id='.$store_id;
			if(M('store_bind_class')->where($where)->count()>0){
				$this->error('该店铺已申请过此类目');
			}
			if(M('store_bind_class')->add($data)){
				adminLog('添加店铺经营类目，类目编号:'.$data['class_3'].',店铺编号:'.$data['store_id']);
				$this->success('添加经营类目成功');exit;
			}else{
				$this->error('操作失败');
			}
		}
		$bind_class_list = M('store_bind_class')->where('store_id='.$store_id)->select();
		$goods_class = M('goods_category')->getField('id,name');
		for($i = 0, $j = count($bind_class_list); $i < $j; $i++) {
			$bind_class_list[$i]['class_1_name'] = $goods_class[$bind_class_list[$i]['class_1']];
			$bind_class_list[$i]['class_2_name'] = $goods_class[$bind_class_list[$i]['class_2']];
			$bind_class_list[$i]['class_3_name'] = $goods_class[$bind_class_list[$i]['class_3']];
		}
		$this->assign('bind_class_list',$bind_class_list);
		$cat_list = M('goods_category')->where("parent_id = 0")->select();
		$this->assign('cat_list',$cat_list);
		$this->display();
	}
	
	
	public function apply_class_save(){
		$data = I('post.');
		if($data['act']== 'del'){
			$r = M('store_bind_class')->where("bid=".$data['del_id'])->delete();
			respose(1);
		}else{
			$data = I('get.');
			$r = M('store_bind_class')->where("bid=".$data['bid'])->save(array('state'=>1));
		}
		if($r){
			$this->success('操作成功',U('Store/apply_class_list'));
		}else{
			$this->error('提交失败');
		}
	}
	
	//店铺申请信息详情
	public function apply_info(){
		$id = I('id');
		$apply = M('store_apply')->where("id=$id")->find();
		$goods_cates = M('goods_category')->getField('id,name,commission');
		if(!empty($apply['store_class_ids'])){
			$store_class_ids = unserialize($apply['store_class_ids']);
			foreach ($store_class_ids as $val){
				$cat = explode(',', $val);
				$bind_class_list[] = array('class_1'=>$goods_cates[$cat[0]]['name'],'class_2'=>$goods_cates[$cat[1]]['name'],
						'class_3'=>$goods_cates[$cat[2]]['name'].'(分佣比例：'.$goods_cates[$cat[2]]['commission'].'%)',
						'value'=>$val,
				);
			}
			$this->assign('bind_class_list',$bind_class_list);
		}
		$this->assign('apply',$apply);
		$apply_log = M('admin_log')->where(array('log_type'=>1))->select();
		$this->assign('apply_log',$apply_log);
		$this->assign('store_grade',M('store_grade')->select());
		$this->display();
	}
	
	//审核店铺开通申请
	public function review(){
		$data = I('post.');
		if($data['id']){
			$apply = M('store_apply')->where(array('id'=>$data['id']))->find();
			if(M('store_apply')->where("id=".$data['id'])->save($data)){
				if($data['apply_state'] == 1){
					
					
					$users = M('users')->where(array('user_id'=>$apply['user_id']))->find();
					$map['password'] = encrypt($apply['contacts_mobile']);//密码默认为客户的手机号
					M('users')->where(array('user_id'=>$apply['user_id']))->save($map);
					if(empty($users)) $this->error('申请会员不存在或已被删除，请检查');
					$store = array('user_id'=>$apply['user_id'],'seller_name'=>$apply['contacts_mobile'],
							'user_name'=>empty($apply['contacts_mobile']) ? $apply['contacts_mobile'] : $apply['contacts_mobile'],
							'grade_id'=>$data['sg_id'],'store_name'=>$apply['store_name'],'store_phone'=>$apply['contacts_mobile'],
							'store_address'=>empty($apply['store_address']) ? '待完善' : $apply['store_address'] ,
							'store_time'=>time(),'store_state'=>1,					
					);

					$store_id = M('store')->add($store);//通过审核开通店铺
					if($store_id){
						$seller = array('seller_name'=>$apply['contacts_mobile'],'user_id'=>$apply['user_id'],
							'group_id'=>0,'store_id'=>$store_id,'is_admin'=>1
						);
						M('seller')->add($seller);//点击店铺管理员
						//绑定商家申请类目
					}
					adminLog($apply['store_name'].'开店申请审核通过',1);
					//短信通知
					sendSms_apply_notice($data['id']);
					
				}else if($data['apply_state'] == 2){
					
					adminLog($apply['store_name'].'开店申请审核未通过，备注信息：'.$data['review_msg'],1);
					
					//短信通知
					sendSms_apply_notice($data['id']);
					
				}
				$this->success('操作成功',U('Store/apply_list'));
			}else{
				$this->error('提交失败');
			}
		}
	}
	
	
	public function reopen_list(){
		$this->assign('store_class',M('store_class')->getField('sc_id,sc_name'));
		$this->display();
	}



    /**
     * 广西授权
     * */
    public function empower(){
        $success = I('success',0);
        if(IS_POST){
            $param = I('');
            $url = C('SYNC_URL')['guangxi'].'/WXAPI/sync/empower';
//            $url = 'http://ceshi.wujing.com/WXAPI/sync/empower';
            $callback = curl_http($url,true,$param);
            Log::record($callback,'DEBUG');
            $data = json_decode($callback,true);
            Log::record(json_encode($param),'DEBUG');
            if($data['status'] == 1){
                //查询绑定没有
                $storeInfo = M('sync_account')->where(['store_id'=>$param['store_id']])->find();
                if(!empty($storeInfo)){
                    $this->success($data['msg']);
                    exit();
                }
                //处理成功做绑定处理
                M('sync_account')->add([
                    'store_id'=>$param['store_id'],
                    'store_name'=>$param['username'],
                    'tag'=>'guangxi',
                    'addtime'=>time()
                ]);
                $this->success($data['msg'],U('/Admin/Store/empower',['success'=>1]));
                exit();
            }else{
                $this->error($data['msg']);
                exit();
            }

        }
        $this->assign('success',$success);
        $this->display();
    }

    /**
     * 取消授权
     * */
    public function revoke(){
        $info = M('sync_account')->where(['store_id'=>I('store_id')])->find();
        if(empty($info)){
            $this->ajaxReturn(array('status' => 0,'msg'=> '非法操作'),'JSON');
            exit();
        }
        M('sync_account')->where(['store_id'=>I('store_id')])->delete();
        $this->ajaxReturn(array('status' => 1,'msg'=> '取消成功'),'JSON');
    }


    /**
     * 黑名单
     */
    public function store_blacklist(){
        $store_id=I('store_id',0);
        $action=I('action');
        $del_id=I('del_id');
        $blacklist =  M('blacklist a')->field('a.id,b.company,b.mobile')->join('ty_users as b ON a.user_id = b.user_id','left')->where('a.store_id='.$store_id)->select();


        if($action=="del"){
            M('blacklist')->where('id='.$del_id)->delete();
            exit;
        }

        if($action=="add"){
            $user_id=I('value');
            $item = M('blacklist')->where(['store_id'=>$store_id,'user_id'=>$user_id])->find();
            if(!$item){
                M('blacklist')->add(['user_id'=>$user_id,'store_id'=>$store_id,'add_time'=>date('Y-m-d H:i:s',time())]);
            }
            exit;
        }



        $this->assign('store_id',$store_id);
        $this->assign('blacklist',$blacklist);
        $this->display();
    }

    /**
     * 店铺客户价格
     */
    public function store_userfloating(){
        $store_id=I('store_id',0);
        $action=I('action');
        $del_id=I('del_id');
        $store_floatinglist =  M('store_floating a')->field('a.id,b.company,b.mobile,a.user_id,a.floating')->join('ty_users as b ON a.user_id = b.user_id','left')->where('a.store_id='.$store_id)->select();
        // dump($store_floatinglist);
        if($action=="del"){
            M('store_floating')->where('id='.$del_id)->delete();
            exit;
        }
        if($action=="add"){
            $user_id=I('value');
            $item = M('store_floating')->where(['store_id'=>$store_id,'user_id'=>$user_id])->find();
            if(!$item){
                M('store_floating')->add(['user_id'=>$user_id,'store_id'=>$store_id,'add_time'=>time()]);
            }
            exit;
        }

        $this->assign('store_id',$store_id);
        $this->assign('store_floating',$store_floatinglist);
        $this->display();
    }

    public function updateStoreFloating(){
        if(IS_POST){
            $store_id = I('store_id');
            $user_id = I('user_id');
            $val = I('val');
            M('store_floating')->where('store_id='.$store_id.' and user_id='.$user_id)->save(['floating'=>$val]);
            $this->ajaxReturn(['code'=>1,'msg'=>'修改成功']);
        }
    }

}